package com.bocloud.cmp.service.app.resource;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.dao.app.ApplicationDao;
import com.bocloud.cmp.dao.app.ApplicationOpenshiftClusterInfoDao;
import com.bocloud.cmp.dao.app.OpenshiftClusterDao;
import com.bocloud.cmp.entity.app.resource.Application;
import com.bocloud.cmp.entity.app.resource.ApplicationOpenshiftClusterInfo;
import com.bocloud.cmp.entity.app.resource.OpenshiftCluster;
import com.bocloud.cmp.interfaces.app.resource.StatisticAppService;
import com.bocloud.cmp.service.utils.OpenshiftUtil;
import com.bocloud.cmp.service.utils.RfcDateTimeParser;
import com.bocloud.common.model.BsmResult;
import com.bocloud.common.utils.DateTools;
import com.bocloud.common.utils.ListTool;

import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerPort;
import io.fabric8.kubernetes.api.model.ContainerStateWaiting;
import io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.Event;
import io.fabric8.kubernetes.api.model.ExecAction;
import io.fabric8.kubernetes.api.model.HTTPGetAction;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.NodeCondition;
import io.fabric8.kubernetes.api.model.ObjectReference;
import io.fabric8.kubernetes.api.model.PersistentVolume;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodSpec;
import io.fabric8.kubernetes.api.model.Probe;
import io.fabric8.kubernetes.api.model.Quantity;
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServicePort;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.VolumeMount;
import io.fabric8.kubernetes.api.model.extensions.Deployment;
import io.fabric8.kubernetes.api.model.extensions.HorizontalPodAutoscaler;
import io.fabric8.kubernetes.client.KubernetesClient;

/**
 * @author Zaney
 * @data:2017年3月9日
 * @describe:页面数据统计业务逻辑层实现
 */
@Component("statisticAppService")
public class StatisticAppServiceImpl implements StatisticAppService {

	private static Logger logger = LoggerFactory.getLogger(StatisticAppServiceImpl.class);

	@Autowired
	private ApplicationDao applicationDao;
	@Autowired
	private OpenshiftClusterDao openshiftClusterDao;
	@Autowired
	private ApplicationOpenshiftClusterInfoDao applicationOpenshiftClusterInfoDao;
	@Autowired
	private OpenshiftUtil openshiftUtil;

	@Override
	public BsmResult total(Long proxyId) {
		// 统计各组件数量
		Map<String, Integer> totalMap = new HashMap<>();
		try {
			// 1、获取集群代理节点信息
			if (null == proxyId) {
				return new BsmResult(true, "该集群不存在");
			}
			OpenshiftCluster query = openshiftClusterDao.query(proxyId);
			// 2、获取client
			KubernetesClient client = openshiftUtil.getKubernetesClient(query.getProxyUrl());
			/**
			 * 3、计算个资源数
			 */
			// Pod
			List<Pod> pods = client.pods().inAnyNamespace().list().getItems();
			totalMap.put("Pod", pods.size());
			// Service
			List<Service> services = client.services().inAnyNamespace().list().getItems();
			totalMap.put("Service", services.size());
			// ReplicationController
			List<ReplicationController> rcs = client.replicationControllers().list().getItems();
			totalMap.put("ReplicationController", rcs.size());
			// PersistentVolume
			List<PersistentVolume> persistentVolumes = client.persistentVolumes().list().getItems();
			totalMap.put("PersistentVolume", persistentVolumes.size());
			// Node
			List<Node> nodes = client.nodes().list().getItems();
			totalMap.put("Node", nodes.size());
			// HPA
			List<HorizontalPodAutoscaler> hpas = client.extensions().horizontalPodAutoscalers().list().getItems();
			totalMap.put("HorizontalPodAutoscaler", hpas.size());
			return new BsmResult(true, totalMap, "获取数据统计信息成功");
		} catch (Exception e) {
			logger.error("list DataBase faile:", e);
			return new BsmResult(false, "获取数据统计信息异常", null, null);
		}
	}

	@Override
	public BsmResult detail(String resourceType, String namespace, String resourceName, Long proxyId) {
		try {
			// 1、获取集群代理节点信息
			if (null == proxyId) {
				return new BsmResult(true, "该集群不存在");
			}
			OpenshiftCluster query = openshiftClusterDao.query(proxyId);
			// 2、获取client
			KubernetesClient client = openshiftUtil.getKubernetesClient(query.getProxyUrl());
			// 判断 根据资源的名称获取资源信息
			switch (resourceType) {
			case "Pod":
				Pod pod = client.pods().inNamespace(namespace).withName(resourceName).get();
				return new BsmResult(true, getPodDetail(pod), "获取Pod信息成功");
			case "ReplicationController":
				ReplicationController replicationController = client.replicationControllers().inNamespace(namespace)
						.withName(resourceName).get();
				return new BsmResult(true, getRcDetail(replicationController), "获取replicationController信息成功");
			case "Service":
				Service service = client.services().inNamespace(namespace).withName(resourceName).get();
				return new BsmResult(true, getServiceDetail(service), "获取Service信息成功");
			case "PersistentVolumes":
				PersistentVolume persistentVolume = client.persistentVolumes().withName(resourceName).get();
				return new BsmResult(true, getPersistentVolumeDetail(persistentVolume), "获取PersistentVolumes信息成功");
			case "HorizontalPodAutoscaler":
				HorizontalPodAutoscaler hpa = client.extensions().horizontalPodAutoscalers().inNamespace(namespace)
						.withName(resourceName).get();
				return new BsmResult(true, getHpaDetail(hpa), "获取HorizontalPodAutoscaler信息成功");
			default: // node or master
				Node node = client.nodes().withName(resourceName).get();
				return new BsmResult(true, getNodeDetail(node), "获取Node/Master信息成功");
			}
		} catch (Exception e) {
			logger.error("获取" + resourceName + "资源详情失败 : ", e);
			return new BsmResult(false, "获取" + resourceName + "资源详情失败", null, null);
		}
	}

	@Override
	public BsmResult resourceList(String resourceType, String resourceName, Integer page, Integer rows, Long appId,
			Long proxyId) {
		try {
			// 1、获取集群代理节点信息
			if (null == proxyId) {
				// 获取应用集群关系表
				ApplicationOpenshiftClusterInfo applicationOpenshiftClusterInfo = applicationOpenshiftClusterInfoDao
						.getApplicationOpenshiftClusterInfo(appId);
				if (null == applicationOpenshiftClusterInfo) {
					logger.warn("该应用未部署,请部署应用");
					return new BsmResult(true, new JSONArray(), "该应用未部署,请部署应用");
				}
				// 获取集群信息
				OpenshiftCluster openshiftCluster = openshiftClusterDao
						.query(applicationOpenshiftClusterInfo.getOpenshiftClusterId());
				if (null == openshiftCluster) {
					logger.warn("没有集群存在");
					return new BsmResult(false, "没有集群存在");
				} else {
					// 走应用平台列表查询
					return getAppResourceList(openshiftCluster, resourceType, resourceName, appId, proxyId);
				}
			} else {// 走kubernetes平台列表查询
				return getKubernetesResourceList(resourceType, resourceName, appId, proxyId);
			}
		} catch (Exception e) {
			logger.error("获取资源列表失败:", e);
			return new BsmResult(false, "获取资源列表失败", null, null);
		}
	}
	

	@Override
	public BsmResult getNodePod(Long proxyId, String nodeName) {
		try {
			//1、获取集群信息
			OpenshiftCluster query = openshiftClusterDao.query(Long.parseLong(proxyId.toString()));
			// 2、获取client
			KubernetesClient client = openshiftUtil.getKubernetesClient(query.getProxyUrl());
			List<Pod> pods = new ArrayList<>();
			pods = client.pods().inAnyNamespace().list().getItems();
			JSONArray resourceList = getNodePod(query.getProxyUrl(), pods, nodeName);
			return new BsmResult(true, resourceList, "获取Pod信息成功");
		} catch (Exception e) {
			logger.error("获取运行实例异常", e);
			return new BsmResult(false, "获取Pod信息异常");
		}
	}

	@Override
	public BsmResult event(String namespace, String resourceType, String resourceName, Long proxyId) {
		try {
			// 1、获取集群代理节点信息
			if (null == proxyId) {
				return new BsmResult(true, "该集群不存在");
			}
			OpenshiftCluster query = openshiftClusterDao.query(Long.parseLong(proxyId.toString()));
			// 2、获取client
			KubernetesClient client = openshiftUtil.getKubernetesClient(query.getProxyUrl());
			// 3、获取资源事件
			List<Map<String, Object>> eventList = new ArrayList<>();
			List<Event> items = client.events().inNamespace(namespace).list().getItems();
			for (Event event : items) {
				Map<String, Object> eventMap = new HashMap<>();
				if (event.getInvolvedObject().getKind().equals(resourceType)) {
					if (event.getInvolvedObject().getName().equals(resourceName)) {
						eventMap.put("name", resourceName);
						eventMap.put("count", event.getCount());
						eventMap.put("kind", event.getInvolvedObject().getKind());
						eventMap.put("type", event.getType());
						eventMap.put("reason", event.getReason());
						eventMap.put("message", event.getMessage());
						eventMap.put("source", event.getSource().getComponent() + "   " + event.getSource().getHost());
						eventMap.put("time", 
										DateTools.formatTime(RfcDateTimeParser.parseDateString(event.getFirstTimestamp())));
						// 将时间转换成时间戳集合
						DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Date date = (Date) fmt.parse(
								DateTools.formatTime(RfcDateTimeParser.parseDateString(event.getFirstTimestamp())));
						eventMap.put("firstTime", date.getTime());
						eventList.add(eventMap);
					}
				}
			}
			if (!ListTool.isEmpty(eventList)) {
				// 按时间从大到小排序
				eventList = getSort(eventList, "firstTime");
			}
			return new BsmResult(true, eventList, "获取成功");
		} catch (Exception e) {
			logger.error("获取 [" + resourceName + "] 事件失败:", e);
			return new BsmResult(false, "获取 [" + resourceName + "] 事件失败");
		}
	}

	@Override
	public BsmResult getLog(String namespace, String resourceName, String containerName, String status, Long proxyId) {
		try {
			// 1、获取集群代理节点信息
			if (null == proxyId) {
				return new BsmResult(true, "该集群不存在");
			}
			OpenshiftCluster query = openshiftClusterDao.query(proxyId);
			// 2、获取client
			KubernetesClient client = openshiftUtil.getKubernetesClient(query.getProxyUrl());
			// 3、返回正常日志信息
			if ("ImagePullBackOff".equals(status) || "ContainerCreating".equals(status)
					|| "ErrImagePull".equals(status) || "RunContainerError".equals(status)) {
				return new BsmResult(true, null, "获取成功");
			}
			String log = client.pods().inNamespace(namespace).withName(resourceName).inContainer(containerName)
					.tailingLines(10).getLog();
			return new BsmResult(true, log, "获取成功");
		} catch (Exception e) {
			logger.error("获取" + resourceName + "日志信息失败 : ", e);
			return new BsmResult(false, "获取" + resourceName + "日志信息失败");
		}
	}

	@Override
	public BsmResult getBarePod(Long proxyId, String nodeName) {
		try {
			// 1、获取集群信息
			OpenshiftCluster query = openshiftClusterDao.query(Long.parseLong(proxyId.toString()));
			// 2、获取client
			KubernetesClient client = openshiftUtil.getKubernetesClient(query.getProxyUrl());
			List<Pod> pods = new ArrayList<>();
			pods = client.pods().inAnyNamespace().list().getItems();
			// 获取该node下所有的pod
			JSONArray resourceList = getNodePod(query.getProxyUrl(), pods, nodeName);
			// 判断该node上有哪些pod是游离状态的
			JSONArray barePods = checkBarePod(client, resourceList);
			return new BsmResult(true, barePods, "获取Pod信息成功");
		} catch (Exception e) {
			logger.error("获取运行实例异常", e);
			return new BsmResult(false, "获取Pod信息异常");
		}
	}

	/**
	 * 获取游离状态的pod
	 * 
	 * @param client
	 * @param resourceList
	 * @return
	 */
	public JSONArray checkBarePod(KubernetesClient client, JSONArray resourceList) {
		JSONArray array = new JSONArray();
		for (Object object : resourceList) {
			JSONObject jsonObject = JSONObject.parseObject(object.toString());
			if (null == jsonObject.get("generateName")) {
				array.add(jsonObject.get("name"));
			}
		}
		return array;
	}

	/* ====================== 获取各资源列表 ============================ */
	private JSONArray getNodeResourceList(List<Node> nodes, String clusterIp, String resourceType,
			String resourceName) {
		JSONArray nodeList = new JSONArray();
		for (Node node : nodes) {
			JSONObject nodeResourceMap = new JSONObject();
			StringBuilder status = new StringBuilder();
			// 逻辑获取节点状态
			List<NodeCondition> conditions = node.getStatus().getConditions();
			for (NodeCondition nodeCondition : conditions) {
				if (nodeCondition.getType().equals("Ready".trim())) {
					if (status.length() > 0) {
						status.append(",");
					}
					status.append(nodeCondition.getType()).append("=").append(nodeCondition.getStatus());
				}
			}
			// 判断master节点是否调度
			if (status.length() > 0) {
				status.append(",").append("SchedulingDisabled").append("=");
			}
			if (node.getSpec().getUnschedulable() != null && node.getSpec().getUnschedulable()) {
				status.append("True");
			} else {
				status.append("False");
			}
			nodeResourceMap.put("status", status);
			nodeResourceMap.put("namespace", node.getMetadata().getNamespace());
			nodeResourceMap.put("name", node.getMetadata().getName());
			nodeResourceMap.put("createTime",
					DateTools.formatTime(RfcDateTimeParser.parseDateString(node.getMetadata().getCreationTimestamp())));
			if (!StringUtils.isEmpty(resourceName)) {// 判断是否是模糊查询
														// resourceName!=null
														// 进行模糊查询
				if (node.getMetadata().getName().contains(resourceName)) {
					nodeList.add(nodeResourceMap);
				}
			} else {
				nodeList.add(nodeResourceMap);
			}
		}
		return nodeList;
	}

	private JSONArray getPersistentVolumeResourceList(List<PersistentVolume> persistentVolumes, String resourceName) {
		JSONArray resourceList = new JSONArray();
		for (PersistentVolume pv : persistentVolumes) {
			JSONObject pvResourceMap = new JSONObject();
			List<String> accessModes = pv.getSpec().getAccessModes();
			StringBuilder accessModeString = new StringBuilder();
			for (String accessMode : accessModes) {
				if (accessModeString.length() > 0) {
					accessModeString.append(",");
				}
				if ("ReadWriteMany".equals(accessMode)) {
					accessModeString.append("读写多次");
				} else {
					accessModeString.append("读写一次");
				}
			}
			// 获取pvc
			ObjectReference claimRef = pv.getSpec().getClaimRef();
			if (null != claimRef) {
				pvResourceMap.put("pvc", claimRef.getName());
			} else {
				pvResourceMap.put("pvc", null);
			}
			// 状态
			if ("bound".equals(pv.getStatus().getPhase())) {
				pvResourceMap.put("status", "绑定");
			} else {
				pvResourceMap.put("status", "发布");
			}
			// 策略
			if ("retain".equals(pv.getSpec().getPersistentVolumeReclaimPolicy())) {
				pvResourceMap.put("reclaimPolicy", "保留");
			} else {
				pvResourceMap.put("reclaimPolicy", "回收");
			}
			pvResourceMap.put("capacity", pv.getSpec().getCapacity().get("storage").getAmount());
			pvResourceMap.put("namespace", pv.getMetadata().getNamespace());
			pvResourceMap.put("name", pv.getMetadata().getName());
			pvResourceMap.put("createTime",
					DateTools.formatTime(RfcDateTimeParser.parseDateString(pv.getMetadata().getCreationTimestamp())));
			pvResourceMap.put("accessMode", accessModeString);
			if (!StringUtils.isEmpty(resourceName)) {// 判断是否是模糊查询
														// resourceName!=null
														// 进行模糊查询
				if (pv.getMetadata().getName().contains(resourceName)) {
					resourceList.add(pvResourceMap);
				}
			} else {
				resourceList.add(pvResourceMap);
			}
		}
		return resourceList;
	}

	private JSONArray getHpaResourceList(List<HorizontalPodAutoscaler> hpas, String resourceName) {
		JSONArray resourceList = new JSONArray();
		for (HorizontalPodAutoscaler hpa : hpas) {
			JSONObject hpaResourceMap = new JSONObject();
			hpaResourceMap.put("namespace", hpa.getMetadata().getNamespace());
			hpaResourceMap.put("name", hpa.getMetadata().getName());
			hpaResourceMap.put("resourceName", hpa.getSpec().getScaleRef().getName());
			hpaResourceMap.put("cpuTargetUtilization", hpa.getSpec().getCpuUtilization().getTargetPercentage());
			hpaResourceMap.put("cpuCurrentUtilization", hpa.getStatus().getCurrentCPUUtilizationPercentage() == null
					? "waiting" : hpa.getStatus().getCurrentCPUUtilizationPercentage());
			hpaResourceMap.put("minReplicas", hpa.getSpec().getMinReplicas());
			hpaResourceMap.put("maxReplicas", hpa.getSpec().getMaxReplicas());
			hpaResourceMap.put("createTime",
					DateTools.formatTime(RfcDateTimeParser.parseDateString(hpa.getMetadata().getCreationTimestamp())));
			if (!StringUtils.isEmpty(resourceName)) {// 判断是否是模糊查询
														// resourceName!=null
														// 进行模糊查询
				if (hpa.getMetadata().getName().contains(resourceName)) {
					resourceList.add(hpaResourceMap);
				}
			} else {
				resourceList.add(hpaResourceMap);
			}
		}
		return resourceList;
	}

	private JSONArray getServiceResourceList(List<Service> services, String resourceName) {
		JSONArray resourceList = new JSONArray();
		for (Service service : services) {
			JSONObject serviceResourceMap = new JSONObject();
			StringBuilder ports = new StringBuilder();
			StringBuilder nodePorts = new StringBuilder();
			for (ServicePort servicePort : service.getSpec().getPorts()) {
				if (ports.length() > 0) {
					ports.append(",");
				}
				ports.append(servicePort.getPort()).append("/").append(servicePort.getProtocol());
				if (nodePorts.length() > 0) {
					nodePorts.append(",");
				}
				if (servicePort.getNodePort() == null) {
					continue;
				}
				nodePorts.append(servicePort.getNodePort());
			}
			serviceResourceMap.put("nodePort", nodePorts.toString());
			serviceResourceMap.put("namespace", service.getMetadata().getNamespace());
			serviceResourceMap.put("name", service.getMetadata().getName());
			serviceResourceMap.put("clusterIp", service.getSpec().getClusterIP());
			serviceResourceMap.put("port", ports.toString());
			serviceResourceMap.put("createTime",
					DateTools.formatTime(RfcDateTimeParser.parseDateString(service.getMetadata().getCreationTimestamp())));
			if (!StringUtils.isEmpty(resourceName)) {// 判断是否是模糊查询
														// resourceName!=null
														// 进行模糊查询
				if (service.getMetadata().getName().contains(resourceName)) {
					resourceList.add(serviceResourceMap);
				}
			} else {
				resourceList.add(serviceResourceMap);
			}
		}
		return resourceList;
	}

	private JSONArray getDeploymentResourceList(List<Deployment> deployments, String resourceName) {
		JSONArray resourceList = new JSONArray();
		for (Deployment deployment : deployments) {
			JSONObject deploymentResourceMap = new JSONObject();
			deploymentResourceMap.put("namespace", deployment.getMetadata().getNamespace());
			deploymentResourceMap.put("name", deployment.getMetadata().getName());
			deploymentResourceMap.put("createTime",
					DateTools.formatTime(
							RfcDateTimeParser.parseDateString(deployment.getMetadata().getCreationTimestamp())));
			deploymentResourceMap.put("desired", deployment.getSpec().getReplicas());
			deploymentResourceMap.put("current", deployment.getStatus().getReplicas());
			deploymentResourceMap.put("upToDate", deployment.getStatus().getUpdatedReplicas());
			deploymentResourceMap.put("available", deployment.getStatus().getAvailableReplicas());
			if (!StringUtils.isEmpty(resourceName)) {// 判断是否是模糊查询
														// resourceName!=null
														// 进行模糊查询
				if (deployment.getMetadata().getName().contains(resourceName)) {
					resourceList.add(deploymentResourceMap);
				}
			} else {
				resourceList.add(deploymentResourceMap);
			}
		}
		return resourceList;
	}

	@SuppressWarnings("unchecked")
	private JSONArray getRcResourceList(List<ReplicationController> rcs, List<Service> services, String resourceName) {
		JSONArray resourceList = new JSONArray();
		JSONArray serviceList = new JSONArray();// 存放service的数据信息
		/**
		 * 获取该应用下所有服务的selector
		 */
		for (Service service : services) {
			Map<String, String> selectorMap = service.getSpec().getSelector();
			JSONArray selectors = new JSONArray();
			if (selectorMap != null) {
				JSONObject object = new JSONObject();
				for (Map.Entry<String, String> entry : selectorMap.entrySet()) {
					selectors.add(entry.toString());
				}
				object.put(service.getMetadata().getName(), selectors);
				serviceList.add(object);
			}
		}
		for (ReplicationController rc : rcs) {
			/**
			 * rc 的 label 与 service 的selector 对比
			 */
			JSONObject rcResourceMap = new JSONObject();
			StringBuffer selectors = new StringBuffer();
			Map<String, String> labelsMap = rc.getSpec().getTemplate().getMetadata().getLabels();
			if (labelsMap != null) {
				for (Map.Entry<String, String> entry : labelsMap.entrySet()) {
					// 判断service里标签选择器是否包含rc的labels中的一个
					for (Object object : serviceList) {
						Map<String, JSONArray> serviceMap = JSONObject.parseObject(object.toString(), Map.class);
						for (Map.Entry<String, JSONArray> service : serviceMap.entrySet()) {
							JSONArray value = service.getValue();
							if (value.contains(entry.toString())) {
								if (null != service.getKey() && !selectors.toString().contains(service.getKey())) {
									if (selectors.length() > 0) {
										selectors.append(",");
									}
									selectors.append(service.getKey());
								}
							}
						}
					}
				}
			}
			rcResourceMap.put("serviceName", selectors.toString());
			rcResourceMap.put("namespace", rc.getMetadata().getNamespace());
			rcResourceMap.put("name", rc.getMetadata().getName());
			rcResourceMap.put("createTime",
					DateTools.formatTime(RfcDateTimeParser.parseDateString(rc.getMetadata().getCreationTimestamp())));
			rcResourceMap.put("desired", rc.getSpec().getReplicas());
			rcResourceMap.put("current", rc.getStatus().getReplicas());
			rcResourceMap.put("available", rc.getStatus().getAvailableReplicas());
			if (!StringUtils.isEmpty(resourceName)) {// 判断是否是模糊查询
														// resourceName!=null
														// 进行模糊查询
				if (rc.getMetadata().getName().contains(resourceName)) {
					resourceList.add(rcResourceMap);
				}
			} else {
				resourceList.add(rcResourceMap);
			}
		}
		return resourceList;
	}

	private JSONArray getPodResourceList(String proxyUrl, List<Pod> pods, String resourceName) {
		JSONArray resourceList = new JSONArray();
		for (Pod pod : pods) {
			JSONArray containers = new JSONArray();
			JSONObject podResourceMap = new JSONObject();
			Integer restartCount = 0;
			String status = null;
			int read = 0;
			StringBuffer image = new StringBuffer();
			List<String> statuss = new ArrayList<String>();
			// 循环pod里所有容器的状态及其其它信息
			List<ContainerStatus> containerStatuses = pod.getStatus().getContainerStatuses();
			List<Container> podContainers = pod.getSpec().getContainers();
			for (int i = 0; i < containerStatuses.size(); i++) {
				JSONObject containerInfo = new JSONObject();
				if (containerStatuses.get(i).getRestartCount() >= restartCount) {
					restartCount = containerStatuses.get(i).getRestartCount();
					ContainerStateWaiting waiting = containerStatuses.get(i).getState().getWaiting();
					if (waiting != null) {
						status = waiting.getReason();
					} else {
						if (containerStatuses.get(i).getState().getTerminated() != null) {
							status = containerStatuses.get(i).getState().getTerminated().getReason();
						} else {
							status = "running";
						}
					}
					statuss.add(status);
				}
				// 准备状态
				if (containerStatuses.get(i).getReady()) {
					read++;
				}
				// 获取pod所有容器信息，添加进集合
				containerInfo.put("name", containerStatuses.get(i).getName());
				String containerId = null;
				if (null != containerStatuses.get(i).getContainerID()) {
					containerId = containerStatuses.get(i).getContainerID().split("//")[1];
					containerInfo.put("containerId", containerId.substring(0, 12));
				} else {
					containerInfo.put("containerId", containerId);
				}
				// 对镜像的处理，多个镜像用“ ，” 隔开
				if (image.length() > 0) {
					image.append(",");
				}
				if (podContainers.get(i).getImage() != null) {
					String imageName = podContainers.get(i).getImage()
							.substring(podContainers.get(i).getImage().lastIndexOf("/") + 1);
					image.append(imageName);
					containerInfo.put("image", imageName);
				}
				containerInfo.put("node", pod.getStatus().getHostIP());
				containerInfo.put("status", status);
				containers.add(containerInfo);
			}
			// 若该pod中，存在多个容器，会存在不健康的容器，那么pod的状态也显示不健康
			for (String stu : statuss) {
				if (!"running".equals(stu)) {
					status = stu;
				}
			}
			podResourceMap.put("containers", containers);
			podResourceMap.put("proxyUrl", proxyUrl);
			podResourceMap.put("images", image);
			podResourceMap.put("namespace", pod.getMetadata().getNamespace());
			podResourceMap.put("name", pod.getMetadata().getName());
			podResourceMap.put("containersReady", read + "/" + statuss.size());// 正常的容器占该pod中所有容器的比例
			podResourceMap.put("status", status);
			podResourceMap.put("restartCount", restartCount);
			podResourceMap.put("createTime",
					DateTools.formatTime(RfcDateTimeParser.parseDateString(pod.getMetadata().getCreationTimestamp())));
			if (!StringUtils.isEmpty(resourceName)) {// 判断是否是模糊查询
														// resourceName!=null
														// 进行模糊查询
				if (pod.getMetadata().getName().contains(resourceName)) {
					resourceList.add(podResourceMap);
				}
			} else {
				resourceList.add(podResourceMap);
			}
		}
		return resourceList;
	}

	/* ====================== 获取各资源详情 ============================ */
	private JSONObject getPodDetail(Pod pod) {
		JSONObject detailMap = new JSONObject();
		// Status
		JSONObject statusMap = new JSONObject();
		JSONArray statusList = new JSONArray();
		statusMap.put("iP", pod.getStatus().getPodIP());
		statusMap.put("node", pod.getSpec().getNodeName());
		statusMap.put("restartPolicy", pod.getSpec().getRestartPolicy());
		statusList.add(statusMap);
		detailMap.put("Status", statusList);
		// Container
		JSONArray containerList = new JSONArray();
		List<ContainerStatus> containerStatuses = pod.getStatus().getContainerStatuses();
		for (ContainerStatus containerStatus : containerStatuses) {
			JSONObject containerMap = new JSONObject();
			containerMap.put("containerName", containerStatus.getName());
			if (containerStatus.getState().getWaiting() != null) {
				containerMap.put("state", containerStatus.getState().getWaiting().getReason());
			} else {
				if (containerStatus.getState().getTerminated() != null) {
					containerMap.put("state", containerStatus.getState().getTerminated().getReason());
				} else {
					containerMap.put("state", "running");
				}
			}
			containerMap.put("ready", containerStatus.getReady());
			containerMap.put("restartCount", containerStatus.getRestartCount());
			containerList.add(containerMap);
		}
		detailMap.put("Container", containerList);
		// Template
		JSONArray templateList = new JSONArray();
		for (Container container : pod.getSpec().getContainers()) {
			JSONObject templateMap = new JSONObject();
			templateMap.put("name", container.getName());
			templateMap.put("image", container.getImage());
			StringBuilder ports = new StringBuilder();
			for (ContainerPort containerPort : container.getPorts()) {
				if (ports.length() > 0) {
					ports.append(",");
				}
				ports.append(containerPort.getContainerPort()).append("/").append(containerPort.getProtocol());
			}
			templateMap.put("ports", ports.toString());
			List<VolumeMount> volumeMounts = container.getVolumeMounts();
			StringBuilder mount = new StringBuilder();
			for (VolumeMount volumeMount : volumeMounts) {
				if (mount.length() > 0) {
					mount.append(",");
				}
				mount.append(volumeMount.getName()).append("->").append(volumeMount.getMountPath());
			}
			templateMap.put("mount", mount.toString());
			// 获取 活性探针 livenessProbe
			Probe livenessProbe = container.getLivenessProbe();
			if (null != livenessProbe) {
				ExecAction exec = livenessProbe.getExec();
				HTTPGetAction httpGet = livenessProbe.getHttpGet();
				if (null != exec) {
					templateMap.put("livenessProbe", exec.getCommand());
				}
				if (null != httpGet) {
					StringBuffer httpGetBuffer = new StringBuffer();
					httpGetBuffer.append("GET ").append(httpGet.getPath()).append(" on port ")
							.append(httpGet.getPort());
					templateMap.put("livenessProbe", httpGetBuffer.toString());
				}
			}
			// 获取 准备探针 readinessProbe
			Probe readinessProbe = container.getReadinessProbe();
			if (null != readinessProbe) {
				ExecAction execAction = readinessProbe.getExec();
				HTTPGetAction httpGetAction = readinessProbe.getHttpGet();
				if (null != execAction) {
					templateMap.put("readinessProbe", execAction.getCommand());
				}
				if (null != httpGetAction) {
					StringBuffer httpGetBuffer = new StringBuffer();
					httpGetBuffer.append("GET ").append(httpGetAction.getPath()).append(" on port ")
							.append(httpGetAction.getPort());
					templateMap.put("readinessProbe", httpGetBuffer.toString());
				}
			}

			// 获取limit
			Map<String, Quantity> limits = container.getResources().getLimits();
			String cpuLimits = null;
			String memoryLimits = null;
			StringBuffer limit = new StringBuffer();
			if (null != limits) {
				if (null != limits.get("cpu")) {
					cpuLimits = limits.get("cpu").getAmount();
					limit.append("cpu").append("=").append(cpuLimits);
				}
				if (null != limits.get("memory")) {
					memoryLimits = limits.get("memory").getAmount();
					limit.append(",").append("memory").append("=").append(memoryLimits);
				}
			}
			templateMap.put("limits", limit.toString());
			// 获取 request
			String cpuRequest = null;
			String memoryRequest = null;
			StringBuffer request = new StringBuffer();
			Map<String, Quantity> requests = container.getResources().getRequests();
			if (null != requests) {
				if (null != requests.get("cpu")) {
					cpuRequest = requests.get("cpu").getAmount();
					request.append("cpu").append("=").append(cpuRequest);
				}
				if (null != requests.get("memory")) {
					memoryRequest = requests.get("memory").getAmount();
					request.append(",").append("memory").append("=").append(memoryRequest);
				}
			}
			templateMap.put("requests", request.toString());

			templateList.add(templateMap);
		}
		detailMap.put("Template", templateList);
		// Volumes
		List<Volume> volumes = pod.getSpec().getVolumes();
		JSONArray volumesList = new JSONArray();
		for (Volume volume : volumes) {
			JSONObject volumesMap = new JSONObject();
			volumesMap.put("volumes", volume.getName());
			if (null != volume.getPersistentVolumeClaim()) {
				volumesMap.put("flag", "flag");
				volumesMap.put("type", "持续卷声明");
				volumesMap.put("claimName", volume.getPersistentVolumeClaim().getClaimName());
				if (null == volume.getPersistentVolumeClaim().getReadOnly()) {
					volumesMap.put("mode", "读写");
				} else {
					volumesMap.put("mode", "只读");
				}
			} else if (null != volume.getEmptyDir()) {
				volumesMap.put("flag", "empty");
				volumesMap.put("type", "empty dir");
				if (null == volume.getEmptyDir().getMedium()) {
					volumesMap.put("medium", "节点默认");
				} else {
					volumesMap.put("medium", volume.getEmptyDir().getMedium());
				}
			} else {
				if (!StringUtils.isEmpty(volume.getSecret())) {
					volumesMap.put("flag", "notFlag");
					volumesMap.put("type", "secret");
					volumesMap.put("secretName", volume.getSecret().getSecretName());
				}
			}
			volumesList.add(volumesMap);
		}
		detailMap.put("Volumes", volumesList);
		return detailMap;
	}

	private JSONObject getRcDetail(ReplicationController rc) {
		JSONObject detailMap = new JSONObject();
		// labels
		Map<String, String> labelMap = rc.getMetadata().getLabels();
		StringBuilder labels = new StringBuilder();
		if (labelMap != null) {
			for (Map.Entry<String, String> entry : labelMap.entrySet()) {
				labels.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
			}
		}
		// selectors
		Map<String, String> selectorMap = rc.getSpec().getSelector();
		StringBuilder selectors = new StringBuilder();
		if (selectorMap != null) {
			for (Map.Entry<String, String> entry : selectorMap.entrySet()) {
				selectors.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
			}
		}
		// image
		StringBuilder images = new StringBuilder();
		List<Container> containers = rc.getSpec().getTemplate().getSpec().getContainers();
		for (Container container : containers) {
			if (images.length() > 0) {
				images.append(",");
			}
			images.append(container.getImage());
		}
		detailMap.put("name", rc.getMetadata().getName());
		detailMap.put("namespace", rc.getMetadata().getNamespace());
		detailMap.put("images", images);
		detailMap.put("labels", labels.toString());
		detailMap.put("selectors", selectors.toString());
		detailMap.put("replicas",
				rc.getStatus().getReplicas() + " 当前运行实例数 / " + rc.getSpec().getReplicas() + " 期望运行实例数");
		return detailMap;
	}

	/**
	 * 获取服务的详情
	 *
	 * @param service
	 * @return
	 */
	private JSONObject getServiceDetail(Service service) {
		JSONObject detailMap = new JSONObject();
		// Basic Details
		JSONObject basicDetailMap = new JSONObject();
		JSONArray basicDetailList = new JSONArray();
		Map<String, String> labelMap = service.getMetadata().getLabels();
		StringBuilder labels = new StringBuilder();
		if (labelMap != null) {
			for (Map.Entry<String, String> entry : labelMap.entrySet()) {
				labels.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
			}
		}
		Map<String, String> selectorMap = service.getSpec().getSelector();
		StringBuilder selectors = new StringBuilder();
		if (selectorMap != null) {
			for (Map.Entry<String, String> entry : selectorMap.entrySet()) {
				selectors.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
			}
		}
		basicDetailMap.put("labels", labels.toString());
		basicDetailMap.put("selectors", selectors.toString());
		basicDetailMap.put("type", service.getSpec().getType());
		basicDetailMap.put("sessionAffinity", service.getSpec().getSessionAffinity());
		basicDetailList.add(basicDetailMap);
		detailMap.put("basicDetails", basicDetailList);
		return detailMap;
	}

	/**
	 * 获取PV详情
	 *
	 * @param persistentVolume
	 * @return
	 */
	private JSONObject getPersistentVolumeDetail(PersistentVolume persistentVolume) {
		JSONObject detailMap = new JSONObject();
		// Basic Details
		JSONObject basicDetailMap = new JSONObject();
		JSONArray basicDetailList = new JSONArray();
		Map<String, String> labelMap = persistentVolume.getMetadata().getLabels();
		StringBuilder labels = new StringBuilder();
		if (labelMap != null) {
			for (Map.Entry<String, String> entry : labelMap.entrySet()) {
				labels.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
			}
		}
		basicDetailMap.put("labels", labels.toString());
		basicDetailMap.put("reclaimPolicy", persistentVolume.getSpec().getPersistentVolumeReclaimPolicy());
		basicDetailMap.put("message", persistentVolume.getStatus().getMessage());
		basicDetailList.add(basicDetailMap);
		detailMap.put("basicDetails", basicDetailList);
		// Source
		JSONObject sourceMap = new JSONObject();
		JSONArray sourceList = new JSONArray();
		sourceMap.put("server", persistentVolume.getSpec().getNfs().getServer());
		sourceMap.put("path", persistentVolume.getSpec().getNfs().getPath());
		if (persistentVolume.getSpec().getNfs().getReadOnly() != null
				&& persistentVolume.getSpec().getNfs().getReadOnly()) {
			sourceMap.put("readOnly", true);
		} else {
			sourceMap.put("readOnly", false);
		}
		sourceList.add(sourceMap);
		detailMap.put("Source", sourceList);
		// pvc
		JSONObject pvcMap = new JSONObject();
		JSONArray pvcList = new JSONArray();
		ObjectReference claimRef = persistentVolume.getSpec().getClaimRef();
		if (null != claimRef) {
			pvcMap.put("pvcName", claimRef.getName());
		}
		pvcList.add(pvcMap);
		detailMap.put("Pvc", pvcList);
		return detailMap;
	}

	/**
	 * 获取hpa的详情
	 *
	 * @param service
	 * @return
	 */
	private JSONObject getHpaDetail(HorizontalPodAutoscaler hpa) {
		JSONObject detailMap = new JSONObject();
		// Basic Details
		JSONObject basicDetailMap = new JSONObject();
		JSONArray basicDetailList = new JSONArray();
		Map<String, String> labelMap = hpa.getMetadata().getLabels();
		StringBuilder labels = new StringBuilder();
		if (labelMap != null) {
			for (Map.Entry<String, String> entry : labelMap.entrySet()) {
				labels.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
			}
		}
		basicDetailMap.put("labels", labels.toString());
		basicDetailList.add(basicDetailMap);
		detailMap.put("basicDetails", basicDetailList);
		return detailMap;
	}

	/**
	 * 获取Node详情
	 *
	 * @param node
	 * @return
	 */
	private JSONObject getNodeDetail(Node node) {
		JSONObject detailMap = new JSONObject();
		// Basic Details
		JSONObject basicDetailMap = new JSONObject();
		JSONArray basicDetailList = new JSONArray();
		Map<String, String> labelsMap = node.getMetadata().getLabels();
		StringBuilder labels = new StringBuilder();
		if (labelsMap != null) {
			for (Map.Entry<String, String> entry : labelsMap.entrySet()) {
				labels.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
			}
		}
		basicDetailMap.put("labels", labels.toString());
		basicDetailMap.put("containerRuntimeVersion", node.getStatus().getNodeInfo().getContainerRuntimeVersion());
		basicDetailMap.put("externalID", node.getSpec().getExternalID());
		basicDetailList.add(basicDetailMap);
		detailMap.put("basicDetails", basicDetailList);
		// Capacity
		JSONObject capacityMap = new JSONObject();
		JSONArray capacityList = new JSONArray();
		capacityMap.put("cpu", node.getStatus().getCapacity().get("cpu").getAmount());
		BigDecimal memory = new BigDecimal(node.getStatus().getCapacity().get("memory").getAmount().split("Ki")[0]);
		memory = memory.divide(new BigDecimal(1e6), 2, RoundingMode.HALF_UP);
		capacityMap.put("memory", memory.toPlainString() + "Gi");
		capacityMap.put("pods", node.getStatus().getCapacity().get("pods").getAmount());
		capacityList.add(capacityMap);
		detailMap.put("capacity", capacityList);
		// Allocatable
		JSONObject allocatablelMap = new JSONObject();
		JSONArray allocatableList = new JSONArray();
		allocatablelMap.put("cpu", node.getStatus().getAllocatable().get("cpu").getAmount());
		BigDecimal mem = new BigDecimal(node.getStatus().getAllocatable().get("memory").getAmount().split("Ki")[0]);
		mem = mem.divide(new BigDecimal(1e6), 2, RoundingMode.HALF_UP);
		allocatablelMap.put("memory", mem.toPlainString() + "Gi");
		allocatablelMap.put("pods", node.getStatus().getAllocatable().get("pods").getAmount());
		allocatableList.add(allocatablelMap);
		detailMap.put("allocatable", allocatableList);
		return detailMap;
	}

	/* =====================获取各资源平台所有的列表========================= */
	/**
	 * 获取kubernetes平台资源列表
	 * 
	 * @param resourceType
	 * @param resourceName
	 * @param appId
	 * @param proxyId
	 * @return
	 */
	public BsmResult getKubernetesResourceList(String resourceType, String resourceName, Long appId, Object proxyId) {
		try {
			OpenshiftCluster query = openshiftClusterDao.query(Long.parseLong(proxyId.toString()));
			// 2、获取client
			KubernetesClient client = openshiftUtil.getKubernetesClient(query.getProxyUrl());
			// 3、判断获取各资源列表
			JSONArray resourceList;
			switch (resourceType) {
			case "Pod": // pod
				List<Pod> pods = new ArrayList<>();
				pods = client.pods().inAnyNamespace().list().getItems();
				resourceList = getPodResourceList(query.getProxyUrl(), pods, resourceName);
				return new BsmResult(true, resourceList, "获取Pod信息成功");
			case "Deployment": // deployment
				List<Deployment> deployments = new ArrayList<>();
				deployments = client.extensions().deployments().inAnyNamespace().list().getItems();
				resourceList = getDeploymentResourceList(deployments, resourceName);
				return new BsmResult(true, resourceList, "获取Deployment信息成功");
			case "ReplicationController": // ReplicationController
				List<ReplicationController> rc = new ArrayList<>();
				rc = client.replicationControllers().inAnyNamespace().list().getItems();
				List<Service> serviceList = new ArrayList<>();
				serviceList = client.services().inAnyNamespace().list().getItems();
				resourceList = getRcResourceList(rc, serviceList, resourceName);
				return new BsmResult(true, resourceList, "获取ReplicationController信息成功");
			case "Service": // service
				List<Service> services = new ArrayList<>();
				services = client.services().inAnyNamespace().list().getItems();
				resourceList = getServiceResourceList(services, resourceName);
				return new BsmResult(true, resourceList, "获取Service信息成功");
			case "PersistentVolumes": // persistentVolumes
				List<PersistentVolume> persistentVolumes = new ArrayList<>();
				persistentVolumes = client.persistentVolumes().list().getItems();
				resourceList = getPersistentVolumeResourceList(persistentVolumes, resourceName);
				return new BsmResult(true, resourceList, "获取PersistentVolume信息成功");
			case "HorizontalPodAutoscaler": // persistentVolumes
				List<HorizontalPodAutoscaler> hpas = new ArrayList<>();
				hpas = client.extensions().horizontalPodAutoscalers().list().getItems();
				resourceList = getHpaResourceList(hpas, resourceName);
				return new BsmResult(true, resourceList, "获取PersistentVolume信息成功");
			default: // node or master
				List<Node> nodes = new ArrayList<>();
				nodes = client.nodes().list().getItems();
				resourceList = getNodeResourceList(nodes, null, resourceType, resourceName);
				return new BsmResult(true, resourceList, "获取Node信息成功");
			}
		} catch (Exception e) {
			logger.error("获取kubernetes资源列表失败:", e);
			return new BsmResult(false, "获取kubernetes资源列表失败");
		}
	}

	/**
	 * 获取应用平台资源列表
	 * 
	 * @param clusters
	 * @param resourceType
	 * @param resourceName
	 * @param appId
	 * @param proxyId
	 * @return
	 */
	public BsmResult getAppResourceList(OpenshiftCluster openshiftCluster, String resourceType, String resourceName,
			Long appId, Object proxyId) {
		JSONArray resourceList = new JSONArray();
		try {
			// 1、获取应用信息
			Application application = null;
			if (null != appId && appId > 0) {
				application = applicationDao.query(appId);
			}
			if (null == application) {
				logger.warn("应用不存在");
				return new BsmResult(false, "应用不存在");
			}
			// 1、获取client
			KubernetesClient client = openshiftUtil.getKubernetesClient(openshiftCluster.getProxyUrl());
			// 2、判断资源
			switch (resourceType) {
			case "Pod": // pod
				List<Pod> pods = new ArrayList<>();
				pods = client.pods().inAnyNamespace().withLabel(OpenshiftUtil.UNIFIED_LABEL_KEY, application.getName())
						.list().getItems();
				resourceList = getPodResourceList(openshiftCluster.getProxyUrl(), pods, resourceName);
				return new BsmResult(true, resourceList, "获取Pod信息成功");
			case "Deployment": // deployment
				List<Deployment> deployments = new ArrayList<>();
				deployments = client.extensions().deployments().inAnyNamespace()
						.withLabel(OpenshiftUtil.UNIFIED_LABEL_KEY, application.getName()).list().getItems();
				resourceList = getDeploymentResourceList(deployments, resourceName);
				return new BsmResult(true, resourceList, "获取Deployment信息成功");
			case "ReplicationController": // ReplicationController
				List<ReplicationController> rcs = new ArrayList<>();
				rcs = client.replicationControllers().inAnyNamespace()
						.withLabel(OpenshiftUtil.UNIFIED_LABEL_KEY, application.getName()).list().getItems();
				List<Service> servicess = new ArrayList<>();
				servicess = client.services().inAnyNamespace()
						.withLabel(OpenshiftUtil.UNIFIED_LABEL_KEY, application.getName()).list().getItems();
				resourceList = getRcResourceList(rcs, servicess, resourceName);
				return new BsmResult(true, resourceList, "获取ReplicationController信息成功");
			case "Service": // service
				List<Service> services = new ArrayList<>();
				services = client.services().inAnyNamespace()
						.withLabel(OpenshiftUtil.UNIFIED_LABEL_KEY, application.getName()).list().getItems();
				resourceList = getServiceResourceList(services, resourceName);
				return new BsmResult(true, resourceList, "获取Service信息成功");
			case "PersistentVolumes": // persistentVolumes
				List<PersistentVolume> persistentVolumes = new ArrayList<>();
				persistentVolumes = client.persistentVolumes()
						.withLabel(OpenshiftUtil.UNIFIED_LABEL_KEY, application.getName()).list().getItems();
				resourceList = getPersistentVolumeResourceList(persistentVolumes, resourceName);
				return new BsmResult(true, resourceList, "获取PersistentVolume信息成功");
			case "HorizontalPodAutoscaler": // hpa
				List<HorizontalPodAutoscaler> hpas = new ArrayList<>();
				hpas = client.extensions().horizontalPodAutoscalers()
						.withLabel(OpenshiftUtil.UNIFIED_LABEL_KEY, application.getName()).list().getItems();
				resourceList = getHpaResourceList(hpas, resourceName);
				return new BsmResult(true, resourceList, "获取Hpa信息成功");
			default: // node or master
				List<Node> nodes = new ArrayList<>();
				nodes = client.nodes().withLabel(OpenshiftUtil.UNIFIED_LABEL_KEY, application.getName()).list()
						.getItems();
				resourceList = getNodeResourceList(nodes, null, resourceType, resourceName);
				return new BsmResult(true, resourceList, "获取Node信息成功");
			}
		} catch (Exception e) {
			logger.error("获取app资源列表失败:", e);
			return new BsmResult(false, "获取app资源列表失败");
		}
	}
	/**
	 * 获取节点下的pod
	 * @param proxyUrl
	 * @param pods
	 * @param nodeName
	 * @return
	 */
	private JSONArray getNodePod(String proxyUrl, List<Pod> pods, String nodeName) {
		JSONArray resourceList = new JSONArray();
		for (Pod pod : pods) {
			PodSpec spec = pod.getSpec();
			// 判断该pod是否被调度
			if (null == spec.getNodeName()) {
				continue;
			}
			// 与节点名相同的pod 就返回页面
			if (spec.getNodeName().equals(nodeName)) {
				// 获取该node下pod的controller名称
				String generateName = pod.getMetadata().getGenerateName();
				JSONObject podResourceMap = new JSONObject();
				Integer restartCount = 0;
				String status = null;
				int read = 0;
				StringBuffer image = new StringBuffer();
				List<String> statuss = new ArrayList<String>();
				// 循环pod里所有容器的状态及其其它信息
				List<ContainerStatus> containerStatuses = pod.getStatus().getContainerStatuses();
				for (ContainerStatus containerStatus : containerStatuses) {
					if (containerStatus.getRestartCount() >= restartCount) {
						restartCount = containerStatus.getRestartCount();
						ContainerStateWaiting waiting = containerStatus.getState().getWaiting();
						if (waiting != null) {
							status = waiting.getReason();
						} else {
							if (containerStatus.getState().getTerminated() != null) {
								status = containerStatus.getState().getTerminated().getReason();
							} else {
								status = "running";
							}
						}
						statuss.add(status);
					}
					// 准备状态
					if (containerStatus.getReady()) {
						read++;
					}
					// 对镜像的处理，多个镜像用“ ，” 隔开
					if (image.length() > 0) {
						image.append(",");
					}
					if (containerStatus.getImage() != null) {
						String imageName = containerStatus.getImage()
								.substring(containerStatus.getImage().lastIndexOf("/") + 1);
						image.append(imageName);
					}
				}
				// 若该pod中，存在多个容器，会存在不健康的容器，那么pod的状态也显示不健康
				for (String stu : statuss) {
					if (!"running".equals(stu)) {
						status = stu;
					}
				}
				// 若无containerStatus 则
				podResourceMap.put("generateName", generateName);
				podResourceMap.put("proxyUrl", proxyUrl);
				podResourceMap.put("images", image);
				podResourceMap.put("namespace", pod.getMetadata().getNamespace());
				podResourceMap.put("name", pod.getMetadata().getName());
				podResourceMap.put("containersReady", read + "/" + statuss.size());// 正常的容器占该pod中所有容器的比例
				podResourceMap.put("status", status);
				podResourceMap.put("restartCount", restartCount);
				podResourceMap.put("createTime", 
						DateTools.formatTime(RfcDateTimeParser.parseDateString(pod.getMetadata().getCreationTimestamp())));
				resourceList.add(podResourceMap);
			}
		}
		return resourceList;
	}

	/**
	 * 时间排序 从大到小
	 * 
	 * @param events
	 * @param sortColunm
	 * @return
	 */
	public List<Map<String, Object>> getSort(List<Map<String, Object>> events, String sortColunm) {
		// 时间排序
		for (int i = 0; i < events.size() - 1; i++) {
			for (int j = 0; j < events.size() - 1 - i; j++) {
				if ((Long) events.get(j).get("firstTime") < (Long) events.get(j + 1).get("firstTime")) {
					Map<String, Object> event = events.get(j);
					events.set(j, events.get(j + 1));
					events.set(j + 1, event);
				}
			}
		}
		return events;
	}

}
